package com.hopedove.callsystem.activity.call;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.callsystem.R;
import com.hopedove.callsystem.adapter.SJZDAdapter;
import com.hopedove.callsystem.databinding.ActivitySavefinishBinding;
import com.hopedove.callsystem.domain.net.EndAffirm;
import com.hopedove.callsystem.domain.net.QueryMachineNoInfo;
import com.hopedove.callsystem.domain.net.QuerySJZD;
import com.hopedove.callsystem.entity.SJZDEntity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.view.SimpleDialog;
import com.hopedove.view.TipsDialogFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class SaveFinishActivity extends BaseActivity implements OnClickListener {
    // 获取任务类型的数据字典id
    private static final String SJZDID_TASKLX = "BQTASKLX";
    //获取完成类型的数据字典id
    private static final String SJZDID_WCLX = "BQWCLX";

    /**
     * 任务类型
     **/
    private String mTaskLx = "";
    /**
     * 完成类型
     **/
    private String mFinishLx = "";
    /**
     * 三联单号
     **/
    private String mMonadNo = "";
    /**
     * 车号
     **/
    private String mMachineNo = "";
    /**
     * 保全工工号
     **/
    private String mBqNo = "";
    /**
     * 保全工姓名
     **/
    private String mBqName = "";

    /**
     * 任务完成状态 记录三联单号状态 1：呼叫中 2:保全中
     ***/
    private String mState = "";
    /**
     * 任务开始时间
     **/
    private String mTaskTime = "";

    /**
     * 任务类型集合
     **/
    private List<SJZDEntity> mTasks = new ArrayList();

    /**
     * 三联单号是否正确
     **/
    private boolean isMonadNoCorrect = false;
    private TipsDialogFragment tipDialog;

    private SJZDAdapter mFinishAdapter;

    List<SJZDEntity> mFinishList = new ArrayList<>();

    private ActivitySavefinishBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySavefinishBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initViewAndEvent();
        initData();
    }


    private void initViewAndEvent() {

        binding.monadNoEt.setText(mMonadNo);
        binding.machineNoEt.setText(mMachineNo);
        mFinishAdapter = new SJZDAdapter(this, mFinishList);
        binding.finishStatusGridView.setAdapter(mFinishAdapter);

        binding.okBtn.setOnClickListener(this);
        binding.cancelBtn.setOnClickListener(this);

        binding.machineNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {

                String machineNo = binding.machineNoEt.getText().toString().trim();
                if (machineNo.length() == 4) {
                    // 查询信息
                    queryMachineNoInfo(machineNo);
                } else {
                    SimpleDialog.show(SaveFinishActivity.this, "车号长度为4位，请重新输入！");
                }
                return true;
            }
            return false;
        });

        mFinishAdapter.setOnBtnClickListener(position -> {
            // 赋值完成类型
            mFinishLx = mFinishList.get(position).SJXZ;
        });
    }

    private void initData() {
        querySJZD(SJZDID_TASKLX);
        querySJZD_WCLX(SJZDID_WCLX);
    }


    private void showTipDialog(View view) {
        if (tipDialog != null) {
            tipDialog.dismiss();
        }
        tipDialog = TipsDialogFragment.newInstance(view);
        tipDialog.setCancelable(false);
        tipDialog.show(getSupportFragmentManager(), "");
    }

    /**
     * 呼叫信息查询
     */
    private void queryMonadNoInfo(String monadNo) {
        showWait();

        Communication.asyncRequest(new QuerySJZD(monadNo), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    Gson gson = new Gson();
                    JSONArray resultArrayDC = jsonObj.optJSONArray("DATADC");
                    List<SJZDEntity> dcTasks = gson.fromJson(resultArrayDC.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    JSONArray resultArrayBQ = jsonObj.optJSONArray("DATABQ");
                    List<SJZDEntity> bcTasks = gson.fromJson(resultArrayBQ.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    mTasks.addAll(dcTasks);
                    mTasks.addAll(bcTasks);
                } catch (JSONException e) {
                    SimpleDialog.show(this, "查询数据字典项失败！");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, "查询数据字典项失败！");
            }
        });
    }

    /**
     *
     */
    private void queryMachineNoInfo(String machineNo) {
        showWait();

        Communication.asyncRequest(new QueryMachineNoInfo(machineNo), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    JSONObject data = jsonObj.optJSONObject("DATA");
                    if (data != null) {
                        isMonadNoCorrect = true;// 查询成功
                        mMonadNo = data.optString("MONADNO");
                        mMachineNo = data.optString("MACHINENO");
                        mBqNo = data.optString("BQNO");
                        mBqName = data.optString("BQNAME");
                        mTaskTime = data.optString("BQKSSJ");
                        mTaskLx = data.optString("TASKLX");
                        mState = data.optString("STATE");

                        if ("1".equals(mState)) {
                            SimpleDialog.show(this, "该三联单号未保全开始！");
                        }
                        binding.machineNoEt.setText(mMachineNo);
                        if (!TextUtils.isEmpty(mTaskTime)) {
                            binding.taskTimeEt.setText(mTaskTime);
                        }
                        if (!TextUtils.isEmpty(mBqNo)) {
                            binding.bqNoEt.setText(mBqNo);
                        }

                        for (int i = 0; i < mTasks.size(); i++) {
                            SJZDEntity task = mTasks.get(i);
                            if (mTaskLx != null && mTaskLx.equals(task.KEYCODE)) {
                                binding.taskLxBtn.setVisibility(View.VISIBLE);
                                binding.taskLxBtn.setText(task.SJXZ);
                                binding.taskLxBtn.setBackground(getDrawableCompat(R.drawable.btn_corner_red));
                            }
                        }
                    } else {
                        SimpleDialog.show(this, "该三联单号还未开始保全！请重新输入！");
                    }

                } catch (JSONException e) {
                    SimpleDialog.show(this, "查询三联单号失败！");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });

    }


    /**
     * 保全完成
     */
    private void saveFinish(String monadNo, String machineNo, String taskLx, String taskState, String bqNo, String BQJSLX, String WCLX) {
        showWait();

        Communication.asyncRequest(new EndAffirm(monadNo, machineNo, taskLx, taskState, bqNo, BQJSLX, WCLX), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    View view = getLayoutInflater().inflate(R.layout.callsys_tips_type_3, null);
                    showTipDialog(view);
                    uiHandler.postDelayed(this::finish, 3000);
                } catch (JSONException e) {
                    e.printStackTrace();
                    SimpleDialog.show(this, "提交失败！！");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 4.4. 查询数据字典
     */
    private void querySJZD(String SJZDID) {
        showWait();
        Communication.asyncRequest(new QuerySJZD(SJZDID), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    Gson gson = new Gson();
                    JSONArray resultArrayDC = jsonObj.optJSONArray("DATADC");
                    List<SJZDEntity> dcTasks = gson.fromJson(resultArrayDC.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    JSONArray resultArrayBQ = jsonObj.optJSONArray("DATABQ");
                    List<SJZDEntity> bcTasks = gson.fromJson(resultArrayBQ.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    mTasks.addAll(dcTasks);
                    mTasks.addAll(bcTasks);
                } catch (JSONException e) {
                    SimpleDialog.show(this, "查询数据字典项失败！");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    private void querySJZD_WCLX(String SJZDID) {
        showWait();
        Communication.asyncRequest(new QuerySJZD(SJZDID), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    Gson gson = new Gson();
                    JSONArray resultArray = jsonObj.optJSONArray("DATA");
                    List<SJZDEntity> finishStatusList = gson.fromJson(resultArray.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    if (finishStatusList != null && finishStatusList.size() > 0) {
                        mFinishList.clear();
                        mFinishList.addAll(finishStatusList);
                        mFinishAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    SimpleDialog.show(this, "查询数据字典项失败！");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.okBtn) {
            mMonadNo = binding.monadNoEt.getText().toString().trim();
            mMachineNo = binding.machineNoEt.getText().toString().trim();
            final String bqNo = binding.bqNoEt.getText().toString().trim().toUpperCase();//转大写       2018年9月19日修改
            if (TextUtils.isEmpty(mMachineNo)) {
                SimpleDialog.show(this, "车号不能为空，请重新输入！");
                return;
            } else if (!"2".equals(mState)) {
                SimpleDialog.show(this, "未保全开始不能提交！");
                return;
            } else if (TextUtils.isEmpty(bqNo)) {
                SimpleDialog.show(this, "保全工工号不能为空，请重新输入！");
                return;
            } else if (TextUtils.isEmpty(mFinishLx)) {
                SimpleDialog.show(this, "请选择工作状态！");
                return;
            } else if (!isMonadNoCorrect) {
                SimpleDialog.show(this, "三联单号校验不成功，请重新输入，查询后再试！");
                return;
            }

            /* 校验是否是同一个人 */
            if (bqNo.equals(mBqNo)) {
                saveFinish(mMonadNo, mMachineNo, mTaskLx, "", bqNo, "1", mFinishLx);
            } else {
                SimpleDialog.forceShow(this, "是否终止 工号：" + mBqNo + "(" + mBqName + ")" + "保全信息?", () -> {
                }, () -> {
                    saveFinish(mMonadNo, mMachineNo, mTaskLx, "", bqNo, "2", mFinishLx);
                });
            }
        } else if (id == R.id.cancelBtn) {
            finish();
        }
    }

}
